import time
from tqsdk import TqApi, TqKq

def start_strategy(api, symbols, lots):
    """
    启动策略主循环
    参数:
        api: 天勤API实例
        symbols: 合约代码列表 (例如: ["SHFE.cu2409", "DCE.m2409"])
        lots: 下单手数
    """
    strategy_running = True
    positions = {}  # 记录各合约的持仓状态
    
    # 获取行情引用
    quotes = {symbol: api.get_quote(symbol) for symbol in symbols}
    
    # 创建持仓字典
    positions = {symbol: api.get_position(symbol) for symbol in symbols}
    
    # 主循环
    while strategy_running and api._loop._running:
        try:
            # 同步等待更新（非协程方式）
            if api.wait_update(deadline=time.time() + 0.5):
                # 遍历所有监控合约
                for symbol in symbols:
                    process_symbol(api, symbol, quotes[symbol], positions[symbol], lots)
        
        except Exception as e:
            print(f"策略异常: {str(e)}")
            break

def process_symbol(api, symbol, quote, position, lots):
    """
    处理单个合约的交易逻辑
    """
    # 检查是否有最新价
    if not quote.datetime.endswith("00"):
        return
    
    # 获取当前持仓
    long_pos = position.pos_long
    short_pos = position.pos_short
    
    # 示例策略：涨买跌卖
    if quote.last_price > quote.upper_limit * 0.6:  # 价格在上半区间
        if long_pos == 0:
            insert_order(api, symbol, "BUY", lots)
            
    elif quote.last_price < quote.lower_limit * 0.4:  # 价格在下半区间
        if short_pos == 0:
            insert_order(api, symbol, "SELL", lots)

def insert_order(api, symbol, direction, volume):
    """
    下单函数（同步方式）
    """
    try:
        order = api.insert_order(
            symbol=symbol,
            direction=direction,
            offset="OPEN",
            volume=volume
        )
        print(f"已提交订单: {symbol} {direction} {volume}手")
        return order
    except Exception as e:
        print(f"下单失败: {str(e)}")
        return None

# 使用示例
if __name__ == "__main__":
    # 初始化连接
    api = TqApi(TqKq(), auth=TqAuth("cps168", "alibaba999"))
    
    # 启动策略
    try:
        start_strategy(
            api=api,
            symbols=["SHFE.cu2409", "DCE.m2409"],
            lots=1
        )
    finally:
        api.close()
